package com.uwantsoft.business.infrastructure;

import com.baidu.yun.core.log.YunLogEvent;
import com.baidu.yun.core.log.YunLogHandler;
import com.baidu.yun.push.auth.PushKeyPair;
import com.baidu.yun.push.client.BaiduPushClient;
import com.baidu.yun.push.constants.BaiduPushConstants;
import com.baidu.yun.push.exception.PushClientException;
import com.baidu.yun.push.exception.PushServerException;
import com.baidu.yun.push.model.*;
import com.uwantsoft.business.service.infrastructure.AppPusher;
import com.uwantsoft.constant.Constant;
import org.apache.log4j.Logger;

/**
 * Use Baidu yun to push message to android apps
 * 1,device type is 3
 * 2,message type: 1 means 通知，2 means 透传消息
 * @author Chuanbao
 */
public class AndroidPusher implements AppPusher {
    private Logger log = Logger.getLogger(AndroidPusher.class);
    private static final String apiKey = "EUrjAa566uk9YsmeqdFEh1N9";
    private static final String secretKey = "GZotZlUsygo4jleYTwQRWEfcommQWazh";
    private BaiduPushClient pushClient;

    public AndroidPusher() {
        PushKeyPair pair = new PushKeyPair(apiKey, secretKey);
        pushClient = new BaiduPushClient(pair,BaiduPushConstants.CHANNEL_REST_URL);
    }

    @Override
    public boolean supported(String deviceType) {
        return Constant.DEVICE_ANDROID.equals(deviceType);
    }

    @Override
    public void pushToSingleDevice(String deviceType, String deviceToken, String message) throws Exception{
        pushClient.setChannelLogHandler(new YunLogHandler() {
            @Override
            public void onHandle(YunLogEvent event) {
                log.debug(event.getMessage());
            }
        });

        try {
            PushMsgToSingleDeviceRequest request = new PushMsgToSingleDeviceRequest()
                    .addChannelId(deviceToken)
                    .addMsgExpires(3600)
                    .addMessageType(1)// 1：通知,0:透传消息. 默认为0 注：IOS只有通知.
                    .addMessage(message)
                    .addDeviceType(3);// deviceType => 3:android, 4:ios
            PushMsgToSingleDeviceResponse response = pushClient.pushMsgToSingleDevice(request);
            log.debug("msgId: " + response.getMsgId() + ",sendTime: "+ response.getSendTime());
        } catch (PushClientException e) {
			log.error("Push client exception:"+e.getMessage());
            throw e;
        } catch (PushServerException e) {
            log.error(String.format("requestId: %d, errorCode: %d, errorMessage: %s",e.getRequestId(), e.getErrorCode(), e.getErrorMsg()));
            throw e;
        }
    }

    public void pushToGroup(String deviceType,String[] deviceTokens,String message) throws Exception{
        pushClient.setChannelLogHandler(new YunLogHandler() {
            @Override
            public void onHandle(YunLogEvent event) {
                log.debug(event.getMessage());
            }
        });

        try {
            PushBatchUniMsgRequest request = new PushBatchUniMsgRequest()
                    .addChannelIds(deviceTokens)
                    .addMsgExpires(3600)
                    .addMessageType(1)
                    .addMessage(message)
                    .addDeviceType(3);
            PushBatchUniMsgResponse response = pushClient.pushBatchUniMsg(request);
            log.debug(String.format("msgId: %s, sendTime: %d",response.getMsgId(), response.getSendTime()));
        } catch (PushClientException e) {
            log.error("Push client exception:"+e.getMessage());
            throw e;
        } catch (PushServerException e) {
            log.error(String.format("requestId: %d, errorCode: %d, errorMessage: %s", e.getRequestId(), e.getErrorCode(), e.getErrorMsg()));
            throw e;
        }
    }

    public void pushToTag(String deviceType,String tag,String message) throws Exception{
        pushClient.setChannelLogHandler(new YunLogHandler() {
            @Override
            public void onHandle(YunLogEvent event) {
                log.debug(event.getMessage());
            }
        });

        try {
            PushMsgToTagRequest request = new PushMsgToTagRequest()
                    .addTagName(tag)
                    .addMsgExpires(3600)
                    .addMessageType(1)
                    .addMessage(message)
                    .addDeviceType(3);
            PushMsgToTagResponse response = pushClient.pushMsgToTag(request);
            log.debug(String.format("msgId: %s, sendTime: %d",response.getMsgId(), response.getSendTime()));
        } catch (PushClientException e) {
            log.error("Push client exception:"+e.getMessage());
            throw e;
        } catch (PushServerException e) {
            log.error(String.format("requestId: %d, errorCode: %d, errorMessage: %s", e.getRequestId(), e.getErrorCode(), e.getErrorMsg()));
            throw e;
        }
    }

}
